#include "deepseekapi.h"
#include <QNetworkRequest>
#include <QUrl>
#include <QDebug>
#include <QProcessEnvironment>

int DeepSeekAPI::s_Id = 0;

DeepSeekAPI::DeepSeekAPI(QObject *parent) : QObject(parent)
{
    manager = new QNetworkAccessManager(this);
    streamReply = nullptr;
    // 获取系统环境变量
    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    apiKey = env.value("DEEPSEEK_API_KEY");
    //connect(manager, &QNetworkAccessManager::finished, this, &DeepSeekAPI::onReplyFinished);
}

void DeepSeekAPI::sendRequest(const QString &message, const QString &conversationId)
{
    curConversationId = conversationId;
    QStringList &arList = mapHistroy[conversationId];
    //QUrl url("https://api.deepseek.com/v1/chat/completions"); // 替换为实际的 API 地址
    QUrl url("https://api.lkeap.cloud.tencent.com/v1/chat/completions");
    QNetworkRequest request(url);

    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setRawHeader("Authorization", QString("Bearer %1").arg(apiKey).toUtf8());

    QJsonArray msgs;
    for (auto his : arList) {
        QStringList info = his.split(":");
        if(info.size() > 1)
        {
            msgs.append({QJsonObject({{"role", info[0]}, {"content", info[1]}})});
        }
    }
    msgs.append({QJsonObject({{"role", "user"}, {"content", message}})});
    QJsonObject json;
    json["model"] = "deepseek-r1"; // 替换为实际的模型名称
    json["messages"] = msgs;
    json["stream"] = true;
    arList.append("user:"+message);

    qDebug() << json;


    QJsonDocument doc(json);
    QByteArray data = doc.toJson();

    // 发送请求
    streamReply = manager->post(request, data);

    // 连接流式输出信号
    connect(streamReply, &QNetworkReply::readyRead, this, &DeepSeekAPI::onReadyRead);
    connect(streamReply, &QNetworkReply::finished, this, &DeepSeekAPI::onReplyFinished);
}

void DeepSeekAPI::onReadyRead()
{
    if (!streamReply) return;

    // 读取部分数据
    QByteArray chunk = streamReply->readAll();
    QString chunkText = QString::fromUtf8(chunk);

    // 解析数据块（假设 API 返回的是 JSON 格式的流式数据）
    if (chunkText.startsWith("data: ")) {
        chunkText = chunkText.mid(6); // 去掉 "data: " 前缀
        if (chunkText.startsWith("[DONE]")) {
            emit responseFinished(curConversationId);
            return;
        }
        QJsonDocument doc = QJsonDocument::fromJson(chunkText.toUtf8());
        if (!doc.isNull()) {
            QJsonObject json = doc.object();
            QString content = json["choices"].toArray().first().toObject()["delta"].toObject()["content"].toString();
            QString reasoning_content =  json["choices"].toArray().first().toObject()["delta"].toObject()["reasoning_content"].toString();
            QString role =  json["choices"].toArray().first().toObject()["delta"].toObject()["role"].toString();
            if(responseText.isEmpty())
            {
                responseText = role + ":";
                emit streamResponseStarted(role, curConversationId); // 发送流式数据
            }
            if(!reasoning_content.isEmpty())
            {
                emit streamResponseReasoningContent(reasoning_content, curConversationId); // 发送流式数据
            }
            else if (!content.isEmpty()) {
                responseText += content;
                emit streamResponseReceived(content, curConversationId); // 发送流式数据
            }
        }
    }
}

void DeepSeekAPI::onReplyFinished()
{
    if (streamReply->error() == QNetworkReply::NoError)
    {
        mapHistroy[curConversationId].append(responseText);
        responseText.clear();
        qDebug() << "Stream finished successfully.";
    }
    else
    {
        qDebug() << "Error:" << streamReply->errorString();
    }

    streamReply->deleteLater();
    streamReply = nullptr;
}
